using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using MauiBuilder.Services;

namespace MauiBuilder.ViewModels;

/// <summary>
/// 功能测试页面视图模型
/// </summary>
public partial class FeatureTestViewModel : BaseViewModel
{

    #region 属性

    /// <summary>
    /// 手电筒状态
    /// </summary>
    [ObservableProperty]
    private bool _isFlashlightOn;

    /// <summary>
    /// 地理位置信息
    /// </summary>
    [ObservableProperty]
    private string _locationInfo = "未获取";

    /// <summary>
    /// 设备状态信息
    /// </summary>
    [ObservableProperty]
    private string _deviceStatus = "准备就绪";

    /// <summary>
    /// 电池信息
    /// </summary>
    [ObservableProperty]
    private string _batteryInfo = "未知";

    /// <summary>
    /// 网络连接状态
    /// </summary>
    [ObservableProperty]
    private string _networkStatus = "未知";

    /// <summary>
    /// 测试结果日志
    /// </summary>
    [ObservableProperty]
    private ObservableCollection<string> _testResults = new();

    /// <summary>
    /// 扫码结果
    /// </summary>
    [ObservableProperty]
    private string _scanResult = "暂无扫码结果";

    /// <summary>
    /// 是否正在执行操作
    /// </summary>
    [ObservableProperty]
    private bool _isBusy;

    #endregion

    #region 构造函数

    private readonly IAppRestartService _restartService;
    
    /// <summary>
    /// 构造函数
    /// </summary>
    public FeatureTestViewModel(IAppRestartService restartService)
    {
        _restartService = restartService;
        InitializeAsync();
    }

    #endregion

    #region 私有方法

    /// <summary>
    /// 初始化异步方法
    /// </summary>
    private void InitializeAsync()
    {
        try
        {
            UpdateDeviceInfo();
            AddTestResult("✅ 页面初始化完成");
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 初始化失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 更新设备信息
    /// </summary>
    private void UpdateDeviceInfo()
    {
        try
        {
            // 获取电池信息
            var battery = Battery.Default;
            BatteryInfo = $"电量：{Math.Round(battery.ChargeLevel * 100, 1)}% | 状态：{GetBatteryStateText(battery.State)} | 电源：{GetPowerSourceText(battery.PowerSource)}";

            // 获取网络状态
            var connectivity = Connectivity.Current;
            NetworkStatus = $"网络：{GetNetworkStatusText(connectivity.NetworkAccess)} | 连接类型：{string.Join(", ", connectivity.ConnectionProfiles.Select(GetConnectionProfileText))}";

            // 获取设备基本信息
            DeviceStatus = $"设备：{DeviceInfo.Current.Name} | 平台：{DeviceInfo.Current.Platform} | 版本：{DeviceInfo.Current.VersionString}";
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 更新设备信息失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 添加测试结果
    /// </summary>
    /// <param name="result">测试结果</param>
    private void AddTestResult(string result)
    {
        var timestamp = DateTime.Now.ToString("HH:mm:ss");
        TestResults.Add($"[{timestamp}] {result}");
        
        // 保持最新50条记录
        while (TestResults.Count > 50)
        {
            TestResults.RemoveAt(0);
        }
    }

    #endregion

    #region 命令方法

    /// <summary>
    /// 切换手电筒命令
    /// </summary>
    [RelayCommand]
    private async Task OnToggleFlashlight()
    {
        try
        {
            IsBusy = true;
            
            if (IsFlashlightOn)
            {
                await Flashlight.Default.TurnOffAsync();
                IsFlashlightOn = false;
                AddTestResult("🔦 手电筒已关闭");
            }
            else
            {
                await Flashlight.Default.TurnOnAsync();
                IsFlashlightOn = true;
                AddTestResult("💡 手电筒已打开");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 手电筒操作失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 获取地理位置命令
    /// </summary>
    [RelayCommand]
    private async Task OnGetLocation()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🌍 正在获取地理位置...");

            var location = await Geolocation.Default.GetLocationAsync(new GeolocationRequest
            {
                DesiredAccuracy = GeolocationAccuracy.Medium,
                Timeout = TimeSpan.FromSeconds(10)
            });

            if (location != null)
            {
                LocationInfo = $"纬度：{location.Latitude:F6} | 经度：{location.Longitude:F6} | 精度：{location.Accuracy:F1}m";
                
                // 尝试获取地址信息
                try
                {
                    var placemarks = await Geocoding.Default.GetPlacemarksAsync(location.Latitude, location.Longitude);
                    var placemark = placemarks?.FirstOrDefault();
                    if (placemark != null)
                    {
                        var address = $"{placemark.CountryName} {placemark.AdminArea} {placemark.Locality} {placemark.Thoroughfare}";
                        LocationInfo += $" | 地址：{address}";
                    }
                }
                catch
                {
                    // 地址解析失败时忽略
                }

                AddTestResult($"✅ 地理位置获取成功：{LocationInfo}");
            }
            else
            {
                LocationInfo = "无法获取位置信息";
                AddTestResult("❌ 地理位置获取失败");
            }
        }
        catch (Exception ex)
        {
            LocationInfo = $"获取失败：{ex.Message}";
            AddTestResult($"❌ 地理位置获取异常：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 触觉反馈命令
    /// </summary>
    [RelayCommand]
    private async Task OnTriggerHapticFeedback()
    {
        try
        {
            IsBusy = true;
            
            // 尝试不同类型的触觉反馈
            HapticFeedback.Default.Perform(HapticFeedbackType.Click);
            await Task.Delay(500);
            HapticFeedback.Default.Perform(HapticFeedbackType.LongPress);
            await Task.Delay(500);
            HapticFeedback.Default.Perform(HapticFeedbackType.Click);
            
            AddTestResult("📳 触觉反馈已触发");
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 触觉反馈失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 打开相机命令
    /// </summary>
    [RelayCommand]
    private async Task OnOpenCamera()
    {
        try
        {
            IsBusy = true;
            AddTestResult("📸 正在打开相机...");

            var photo = await MediaPicker.Default.CapturePhotoAsync();
            if (photo != null)
            {
                // 获取照片信息
                var fileInfo = new FileInfo(photo.FullPath);
                AddTestResult($"✅ 照片拍摄成功，文件大小：{fileInfo.Length / 1024}KB，路径：{photo.FullPath}");
            }
            else
            {
                AddTestResult("📸 照片拍摄已取消");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 相机操作失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 选择照片命令
    /// </summary>
    [RelayCommand]
    private async Task OnPickPhoto()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🖼️ 正在选择照片...");

            var photo = await MediaPicker.Default.PickPhotoAsync();
            if (photo != null)
            {
                var fileInfo = new FileInfo(photo.FullPath);
                AddTestResult($"✅ 照片选择成功，文件大小：{fileInfo.Length / 1024}KB，路径：{photo.FullPath}");
            }
            else
            {
                AddTestResult("🖼️ 照片选择已取消");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 照片选择失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 屏幕截图命令
    /// </summary>
    [RelayCommand]
    private async Task OnTakeScreenshot()
    {
        try
        {
            IsBusy = true;
            AddTestResult("📱 正在截取屏幕...");

            var screenshot = await Screenshot.Default.CaptureAsync();
            if (screenshot != null)
            {
                // 保存截图到应用目录
                var fileName = $"screenshot_{DateTime.Now:yyyyMMdd_HHmmss}.png";
                var filePath = Path.Combine(FileSystem.Current.AppDataDirectory, fileName);
                
                using var sourceStream = await screenshot.OpenReadAsync();
                using var fileStream = File.Create(filePath);
                await sourceStream.CopyToAsync(fileStream);
                
                AddTestResult($"✅ 屏幕截图已保存：{filePath}");
            }
            else
            {
                AddTestResult("❌ 屏幕截图失败");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 屏幕截图异常：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }



    /// <summary>
    /// 分享内容命令
    /// </summary>
    [RelayCommand]
    private async Task OnShareContent()
    {
        try
        {
            IsBusy = true;
            AddTestResult("📤 正在分享内容...");

            await Share.Default.RequestAsync(new ShareTextRequest
            {
                Text = "我正在使用 MAUI 应用进行功能测试！",
                Title = "分享测试"
            });

            AddTestResult("✅ 分享面板已打开");
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 分享失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 检查网络连接命令
    /// </summary>
    [RelayCommand]
    private void OnCheckNetworkConnection()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🌐 正在检查网络连接...");

            var connectivity = Connectivity.Current;
            var networkStatus = connectivity.NetworkAccess;
            var profiles = connectivity.ConnectionProfiles;

            var statusText = GetNetworkStatusText(networkStatus);
            var profilesText = string.Join(", ", profiles.Select(GetConnectionProfileText));

            AddTestResult($"📶 网络状态：{statusText}");
            AddTestResult($"🔗 连接类型：{profilesText}");

            // 更新显示
            UpdateDeviceInfo();
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 网络检查失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 检查设备功能支持命令
    /// </summary>
    [RelayCommand]
    private async Task OnCheckDeviceFeatures()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🔍 正在进行设备功能检查...");
            
            AddTestResult("📊 功能支持情况检查:");
            
            var features = new Dictionary<string, (bool supported, string status)>();
            
            // 检查其他功能
            try 
            {
                bool flashlightSupported = await Flashlight.Default.IsSupportedAsync();
                features.Add("手电筒功能", (flashlightSupported, flashlightSupported ? "支持" : "不支持"));
            }
            catch (Exception ex)
            {
                features.Add("手电筒功能", (false, $"检查失败: {ex.Message}"));
            }
            
            features.Add("地理位置功能", (true, "默认支持（需要权限）"));
            
            try 
            {
                bool cameraSupported = MediaPicker.Default.IsCaptureSupported;
                features.Add("相机功能", (cameraSupported, cameraSupported ? "支持" : "不支持"));
            }
            catch (Exception ex)
            {
                features.Add("相机功能", (false, $"检查失败: {ex.Message}"));
            }
            
            try 
            {
                bool hapticSupported = HapticFeedback.Default.IsSupported;
                features.Add("触觉反馈功能", (hapticSupported, hapticSupported ? "支持" : "不支持"));
            }
            catch (Exception ex)
            {
                features.Add("触觉反馈功能", (false, $"检查失败: {ex.Message}"));
            }
            
            // 输出功能检查结果
            foreach (var feature in features)
            {
                var emoji = feature.Value.supported ? "✅" : "❌";
                AddTestResult($"{emoji} {feature.Key}: {feature.Value.status}");
            }
            
            // 统计支持情况
            var totalSupported = features.Count(f => f.Value.supported);
            var totalCount = features.Count;
            AddTestResult($"📊 功能支持统计：{totalSupported}/{totalCount} 项功能可用");
            
            if (totalSupported < totalCount)
            {
                AddTestResult("💡 不支持的功能将提供替代方案（如复制到剪贴板）");
                AddTestResult("🎯 模拟器环境限制是正常现象，真实设备通常支持更多功能");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 检查设备功能失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 检查权限状态命令
    /// </summary>
    [RelayCommand]
    private async Task OnCheckPermissions()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🔑 正在检查应用权限...");

            // 检查各种权限
            var permissions = new Dictionary<string, PermissionStatus>
            {
                {"相机", await Permissions.CheckStatusAsync<Permissions.Camera>()},
                {"位置", await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>()},
                {"存储", await Permissions.CheckStatusAsync<Permissions.StorageRead>()},
                {"麦克风", await Permissions.CheckStatusAsync<Permissions.Microphone>()},
                {"照片", await Permissions.CheckStatusAsync<Permissions.Photos>()}
            };

            foreach (var permission in permissions)
            {
                var statusText = GetPermissionStatusText(permission.Value);
                AddTestResult($"🔐 {permission.Key}权限：{statusText}");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 权限检查失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 扫码命令
    /// </summary>
    [RelayCommand]
    private async Task OnScanBarcode()
    {
        try
        {
            IsBusy = true;
            AddTestResult("📱 正在检查相机权限...");

            // 检查相机权限
            var status = await Permissions.CheckStatusAsync<Permissions.Camera>();
            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.Camera>();
                if (status != PermissionStatus.Granted)
                {
                    AddTestResult("❌ 相机权限被拒绝，无法进行扫码");
                    ScanResult = "相机权限被拒绝";
                    return;
                }
            }

            AddTestResult("📱 正在打开扫码界面...");
            
            // 打开扫码页面
            var scanPage = new MauiBuilder.Views.BarcodeScanPage();
            await Shell.Current.Navigation.PushAsync(scanPage);
            
            // 等待扫码结果
            var result = await scanPage.WaitForScanResultAsync();

            if (result != null && !string.IsNullOrWhiteSpace(result.Value))
            {
                ScanResult = $"扫码结果：{result.Value}";
                AddTestResult($"✅ 扫码成功：{result.Value}");
                AddTestResult($"📱 扫码格式：{result.Format.ToString()}");
                
                // 如果是网址，可以提供打开选项
                if (result.Value.StartsWith("http://") || result.Value.StartsWith("https://"))
                {
                    var openUrl = await AppShell.DisplayConfirmAsync("扫码结果", 
                        $"检测到网址：{result.Value}\n\n是否打开此网址？", "打开", "取消");
                    
                    if (openUrl == true)
                    {
                        await Browser.Default.OpenAsync(result.Value, BrowserLaunchMode.SystemPreferred);
                        AddTestResult($"🌍 已打开网址：{result.Value}");
                    }
                }
            }
            else
            {
                ScanResult = "扫码被取消或没有识别到任何二维码";
                AddTestResult("❌ 扫码被取消或没有识别到任何二维码");
            }
        }
        catch (Exception ex)
        {
            ScanResult = $"扫码失败：{ex.Message}";
            AddTestResult($"❌ 扫码失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 清空测试结果命令
    /// </summary>
    [RelayCommand]
    private void OnClearTestResults()
    {
        TestResults.Clear();
        AddTestResult("🧹 测试结果已清空");
    }

    /// <summary>
    /// 刷新设备信息命令
    /// </summary>
    [RelayCommand]
    private void OnRefreshDeviceInfo()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🔄 正在刷新设备信息...");
            UpdateDeviceInfo();
            AddTestResult("✅ 设备信息已更新");
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 刷新失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }

    /// <summary>
    /// 重启应用命令
    /// </summary>
    [RelayCommand]
    private async Task OnRestartApp()
    {
        try
        {
            IsBusy = true;
            AddTestResult("🔄 正在重启应用...");

            // 显示确认对话框
            bool confirm = await AppShell.DisplayConfirmAsync(
                "重启应用", 
                "确定要重启应用吗？未保存的数据将会丢失。", 
                "确定", 
                "取消");

            if (confirm)
            {
                // 显示重启中提示
                await ShowRestartInProgressAsync();
                await Task.Delay(1000);

                // 执行重启
                await _restartService.RestartAppAsync();
            }
            else
            {
                AddTestResult("↩️ 重启操作已取消");
            }
        }
        catch (Exception ex)
        {
            AddTestResult($"❌ 重启应用失败：{ex.Message}");
        }
        finally
        {
            IsBusy = false;
        }
    }


    #endregion

    #region 辅助方法

    private async Task ShowRestartInProgressAsync()
    {
        var restartPage = new ContentPage
        {
            BackgroundColor = Color.FromArgb("#2196F3"),
            Content = new VerticalStackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center,
                Spacing = 20,
                Children =
                {
                    new ActivityIndicator
                    {
                        IsRunning = true,
                        Color = Colors.White,
                        Scale = 1.5
                    },
                    new Label
                    {
                        Text = "应用重启中...",
                        TextColor = Colors.White,
                        FontSize = 18,
                        HorizontalOptions = LayoutOptions.Center
                    }
                }
            }
        };

        await Shell.Current.Navigation.PushModalAsync(restartPage);

        // 短暂显示后执行重启
        await Task.Delay(1500);
    }
    /// <summary>
    /// 获取电池状态文本
    /// </summary>
    private string GetBatteryStateText(BatteryState state) => state switch
        {
            BatteryState.Charging => "充电中",
            BatteryState.Discharging => "放电中",
            BatteryState.Full => "已充满",
            BatteryState.NotCharging => "未充电",
            BatteryState.NotPresent => "无电池",
            _ => "未知"
        };

    /// <summary>
    /// 获取电源类型文本
    /// </summary>
    private string GetPowerSourceText(BatteryPowerSource source) => source switch
        {
            BatteryPowerSource.Battery => "电池",
            BatteryPowerSource.AC => "交流电",
            BatteryPowerSource.Usb => "USB",
            BatteryPowerSource.Wireless => "无线充电",
            _ => "未知"
        };

    /// <summary>
    /// 获取网络状态文本
    /// </summary>
    private string GetNetworkStatusText(NetworkAccess access) => access switch
        {
            NetworkAccess.Internet => "已连接",
            NetworkAccess.ConstrainedInternet => "受限连接",
            NetworkAccess.Local => "本地网络",
            NetworkAccess.None => "无连接",
            _ => "未知"
        };

    /// <summary>
    /// 获取连接类型文本
    /// </summary>
    private string GetConnectionProfileText(ConnectionProfile profile) => profile switch
        {
            ConnectionProfile.Bluetooth => "蓝牙",
            ConnectionProfile.Cellular => "移动网络",
            ConnectionProfile.Ethernet => "以太网",
            ConnectionProfile.WiFi => "WiFi",
            _ => "其他"
        };

    /// <summary>
    /// 获取权限状态文本
    /// </summary>
    private string GetPermissionStatusText(PermissionStatus status) => status switch
        {
            PermissionStatus.Granted => "已授权",
            PermissionStatus.Denied => "被拒绝",
            PermissionStatus.Disabled => "已禁用",
            PermissionStatus.Restricted => "受限制",
            _ => "未知"
        };

    #endregion
    }